package com.thinktank.dao;


import java.sql.*;

import com.thinktank.vo.*;

import static com.thinktank.util.DbUtil.*;

public class MemberDao {
	public Connection con = null;
	
	public MemberDao(Connection con){
		super();
		this.con = con;
	}
	
	public int InsertMember(Member member) throws SQLException{
		
		PreparedStatement ps = null;
		int result = 0;
		try {
			String temp = "select Max(mb_no) from MEMBER";
			ps = con.prepareStatement(temp);
			ResultSet rs = ps.executeQuery();
			rs.next();
			
			int number = rs.getInt(1)+1;
			rs.close();
			
			String query = "INSERT INTO MEMBER VALUES(?, ?, ?, ?, ?, ?, ?)";
			ps = con.prepareStatement(query);

			ps.setInt(1, number);
			ps.setString(2, member.getmMail());
			ps.setString(3, member.getmName());
			ps.setString(4, member.getmPass());
			ps.setString(5, member.getmDate());
			ps.setString(6, member.getmGender());
			ps.setString(7, member.getmPage());
			
			result = ps.executeUpdate();
			ps.close();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			
		}
		if(result != 0)		commit(con);
		return result;
	}
	
	public Member login(String email, String password){
		PreparedStatement ps = null;
		
		Member member = null;
		try {
			String sql = "select * from MEMBER WHERE (MB_MAIL = ?) AND (MB_PASS = ?)";
			ps = con.prepareStatement(sql);
			ps.setString(1, email);
			ps.setString(2, password);
			ResultSet rs = ps.executeQuery();
			
			
			while(rs.next()){
				member = new Member();
				member.setmMail(rs.getString("MB_MAIL"));
				member.setmNo(rs.getInt("MB_NO"));
				member.setmDate(rs.getString("MB_BIRTH"));
				member.setmPass(rs.getString("MB_PASS"));
				member.setmGender(rs.getString("MB_GENDER"));
				member.setmName(rs.getString("MB_NAME"));
				member.setmPage(rs.getString("MB_PAGE"));
			}
			close(rs);
			close(ps);
		} catch (Exception e) {
			e.printStackTrace();
		} 
		
		return member;
	}
	
	public Member cookieLogin(String no){
		PreparedStatement ps = null;
		
		Member member = null;
		try {
			String sql = "select * from MEMBER WHERE MB_NO = ?";
			ps = con.prepareStatement(sql);
			ps.setString(1, no);
			ResultSet rs = ps.executeQuery();
			
			while(rs.next()){
				member = new Member();
				member.setmMail(rs.getString("MB_MAIL"));
				member.setmNo(rs.getInt("MB_NO"));
				member.setmDate(rs.getString("MB_BIRTH"));
				member.setmPass(rs.getString("MB_PASS"));
				member.setmGender(rs.getString("MB_GENDER"));
				member.setmName(rs.getString("MB_NAME"));
				member.setmPage(rs.getString("MB_PAGE"));
			}
			close(rs);
			close(ps);
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		return member;
	}
}
